package durst.data.json;

import java.sql.SQLException;
import java.text.SimpleDateFormat;

import com.sdicons.json.mapper.JSONMapper;
import com.sdicons.json.mapper.MapperException;
import com.sdicons.json.mapper.helper.SimpleMapperHelper;
import com.sdicons.json.model.JSONObject;
import com.sdicons.json.model.JSONValue;

import durst.data.Account;
import durst.data.CSDMessage;
import durst.data.dao.DaoFactory;

public class MessageJSONHelper implements SimpleMapperHelper {
	private static SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yy hh:mma");
	
	@Override
	public Class<CSDMessage> getHelpedClass() {
		return CSDMessage.class;
	}

	@Override
	public JSONValue toJSON(Object aPojo) throws MapperException {
		if (aPojo instanceof CSDMessage && aPojo != null) {
			CSDMessage message = (CSDMessage)aPojo;
			JSONObject ret = new JSONObject(); 

			if (message.getTitle() == null) {
				try {
					DaoFactory.getInstance().createDao(CSDMessage.class).refresh(message);
				} catch (SQLException e) {
					throw new MapperException("could not refresh Message object from DB!");
				}
			}
			if (message.getSender() == null || message.getSender().getFirstName() == null) {
				try {
					DaoFactory.getInstance().createDao(Account.class).refresh(message.getSender());
				} catch (SQLException e) {
					throw new MapperException("could not refresh Sender object from DB!");
				}
			}
			if (message.getTarget() == null || message.getTarget().getFirstName() == null) {
				try {
					DaoFactory.getInstance().createDao(Account.class).refresh(message.getTarget());
				} catch (SQLException e) {
					throw new MapperException("could not refresh Target object from DB!");
				}
			}
			
			String[] columns = new String[4];
			columns[0] = message.getTitle();
			columns[1] = message.getSender().getFullName();
			columns[2] = message.getTarget().getFullName();
			columns[3] = formatter.format(message.getSent());
			
			ret.getValue().put("id", JSONMapper.toJSON(message.getId()));
			ret.getValue().put("columns", JSONMapper.toJSON(columns));
			ret.getValue().put("read", JSONMapper.toJSON(message.isRead()));
			return ret;
		}
		return null;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public Object toJava(JSONValue arg0, Class arg1) throws MapperException {
		// TODO Auto-generated method stub
		return null;
	}

}
